/**
 * 
 */
package edu.gtcfla.km.admin.appmodules.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresUser;
import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.vsg.biz.BusinessEntityFactory;
import org.vsg.biz.BusinessOperationException;
import org.vsg.biz.account.User;
import org.vsg.common.i18n.I18nMessageService;
import org.vsg.common.web.json.ListResult;
import org.vsg.common.web.json.SubmitResult;
import org.vsg.search.api.criterion.MapPaginaitionCriteria;
import org.vsg.search.api.criterion.PaginationCriteria;
import org.vsg.search.api.criterion.SearchCriteriaCls;
import org.vsg.security.annotation.RegisterRequestPermissionStrategy;

import edu.gtcfla.km.admin.appmodules.service.RoleService;
import edu.gtcfla.km.admin.appmodules.service.UserService;
import edu.gtcfla.km.admin.appmodules.vo.SysUserFormVO;
import edu.gtcfla.km.admin.appmodules.vo.SysUserListVO;
import edu.gtcfla.km.admin.appmodules.vo.UserRoleAssignedFormVO;
import edu.gtcfla.km.core.ApplicationConstant;

/**
 * @author Bill Vison
 *
 */
@Controller
@Lazy
@RequestMapping(ApplicationConstant.DATA_RERESOURCE)
public class UserController {

	private final static Logger logger = LoggerFactory.getLogger(ModuleController.class);	
	
	private final String modulePath = "/user";
		
	@Autowired(required=false)
	private I18nMessageService i18nMessageService;	

	@Autowired(required=false)
	private RoleService roleService;

	@Autowired(required=false)
	private UserService sysUserService;

	@Autowired	
	private BusinessEntityFactory entityFactory;		
	

	@SuppressWarnings("unchecked")
	@SearchCriteriaCls(
		criteriaClass = MapPaginaitionCriteria.class
	)	
	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = "pageUser.json",
		skipCheck = true
	)		
	@RequestMapping(value = modulePath +  "/paging.json")
	public @ResponseBody ListResult accessPageUsers(PaginationCriteria criteria,HttpServletRequest request) throws Exception {
		Page<SysUserListVO> page = sysUserService.pageUsers(criteria);
		ListResult lr = new ListResult();
		lr.setRows(page.getContent());
		lr.setResults((int) page.getTotalElements());
		return lr;
	}	

	
	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = "load_simpleuser.json",
		skipCheck = true
	)		
	@RequestMapping(value = modulePath + "/load_simpleuser.json")
	public @ResponseBody SubmitResult accessLoadSimpleUser(String userId) throws Exception {

		SubmitResult submitResult = new SubmitResult();
		if (userId != null) {
			
			try {
				SysUserFormVO user = sysUserService.loadUser( userId );
				
				submitResult.setSuccess(true);
				submitResult.setData( user );
				
			} catch (BusinessOperationException boe) {
				
				boe.printStackTrace();
				
			}
						
		} else {
			submitResult.setMsg(" load entity ID is null " );
		}

		return submitResult;	
	}	


	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = "submit_deleteusers.json",
		skipCheck = true
	)		
	@RequestMapping(value = modulePath +  "/submit_deleteall.json")
	public @ResponseBody SubmitResult accessDeleteUsers(@RequestBody List<String> receiveValues) throws Exception {
		
		
		// --- map to json object data ---
		SubmitResult result = new SubmitResult();
			
			// --- remove user id ---
			try {
				if ( receiveValues != null && !receiveValues.isEmpty() ) {
					
					sysUserService.deleteUsers( receiveValues.toArray(new String[0]) );

				}			
				result.setSuccess(true);				

				String msg = i18nMessageService.getMessage("module-admin.user.delete.success", null);
				result.setMsg(msg);
				
			} catch (BusinessOperationException se) {
				// TODO Auto-generated catch block
				se.printStackTrace();
				result.setSuccess(false);
				String msg = i18nMessageService.getMessage("module-admin.user.delete.success", null);
				result.setMsg(msg);				
			}



		return result;
	}
	

	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = "submit_adduser.json",
		skipCheck = true
	)		
	@RequestMapping(value = modulePath + "/submit_adding.json")
	public @ResponseBody SubmitResult accessAddUser(SysUserFormVO user) throws Exception {
		
		
		// --- map to json object data ---
		SubmitResult result = new SubmitResult();
		try {
			
			sysUserService.addUser(user);
			result.setSuccess(true);
			String msg = i18nMessageService.getMessage("module-admin.user.add.success", null);
			result.setMsg(msg);
			
		} catch (ServiceException e) {

			e.printStackTrace();
			result.setSuccess(false);
			String msg = i18nMessageService.getMessage("module-admin.user.add.error", null);
			result.setMsg(msg);

		
		}



		return result;
	}
	
	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = "submit_updateuser.json",
		skipCheck = true
	)		
	@RequestMapping(value = modulePath + "/submit_updating.json")
	public  @ResponseBody SubmitResult accessUpdateUser(SysUserFormVO user) throws Exception {
		
		
		// --- map to json object data ---
		SubmitResult result = new SubmitResult();
		
		try {
			
			sysUserService.updateUser(user);
			result.setSuccess(true);
			String msg = i18nMessageService.getMessage("module-admin.user.update.success", null);
			result.setMsg(msg);
			
		} catch (ServiceException e) {

			e.printStackTrace();
			result.setSuccess(false);
			String msg = i18nMessageService.getMessage("module-admin.user.update.error", null);
			result.setMsg(msg);

		
		}



		return result;
	}
	
	

	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = "/user/role/submit_assign.json",
		skipCheck = true
	)		
	@RequestMapping(value = modulePath +"/role/submit_assign.json")
	public @ResponseBody SubmitResult accessSubmitSelectedRoles(String id ,String selectedRoles) throws Exception {
		
		
		// --- map to json object data ---
		SubmitResult result = new SubmitResult();

		try {
			
			User user = entityFactory.create(User.class);
			user.setId( id );
			
			String[] roleIds = selectedRoles.split(",");
			
			sysUserService.assignedRoles(roleIds , user );

			result.setSuccess(true);
			String msg = i18nMessageService.getMessage("module-admin.user.assignroles.success", null);
			result.setMsg(msg);
			
		} catch (Exception e) {

			e.printStackTrace();
			result.setSuccess(false);
			String msg = i18nMessageService.getMessage("module-admin.user.assignroles.error", null);
			result.setMsg(msg);

		
		}
		return result;
	}	

	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = "/user/role/load_assigned.json",
		skipCheck = true
	)		
	@RequestMapping(value = modulePath + "/role/load_assigned.json")
	public @ResponseBody SubmitResult accessLoadAssignUser(String userId) throws Exception {

		SubmitResult submitResult = new SubmitResult();
		if (userId != null) {
			
			try {
				UserRoleAssignedFormVO user = sysUserService.loadRoleAssignedForm( userId );
				
				submitResult.setSuccess(true);
				submitResult.setData( user );
				
			} catch (BusinessOperationException boe) {
				
				boe.printStackTrace();
				
			}
						
		} else {
			submitResult.setMsg(" load entity ID is null " );
		}

		return submitResult;	
	}	
	
	
}
